<template>
  <div class="trend-chart-card">
    <div class="chart-header">
      <div class="chart-title">浏览量折线图</div>
    </div>
    <div class="chart-container" ref="chartRef"></div>
  </div>
</template>

<script setup>
import { ref, inject, onMounted, watch, computed } from 'vue'
import * as echarts from 'echarts'
import { getTodayVisits, getMonthlyVisits } from '@/api/assets/visit'

// 从父组件注入数据
const statisticsData = inject('statisticsData')
const chartRef = ref(null)
let chart = null
const visitData = ref([])
const monthlyVisits = ref([])

// 获取访问记录数据
const getVisitData = async () => {
  try {
    const res = await getTodayVisits()
    if (res.code === 200 && res.data) {
      // 直接使用返回数据或处理数据结构
      visitData.value = res.data
    }
    
    // 获取月度访问量趋势
    const monthlyRes = await getMonthlyVisits()
    if (monthlyRes.code === 200 && monthlyRes.data) {
      monthlyVisits.value = monthlyRes.data
    }
  } catch (error) {
    console.error('获取访问数据失败', error)
  }
}

// 从后端数据中提取月度访问趋势数据
const visitTrends = computed(() => {
  // 优先使用专门的访问趋势API数据
  if (monthlyVisits.value && monthlyVisits.value.length > 0) {
    // 确保月份数据按时间顺序排序
    const sortedVisits = [...monthlyVisits.value].sort((a, b) => {
      const aDate = a.month
      const bDate = b.month
      return aDate.localeCompare(bDate)
    })
    
    const months = sortedVisits.map(item => item.month)
    const visitData = sortedVisits.map(item => item.visit_count)
    return { months, visitData }
  }
  
  // 其次使用statisticsData中的访问趋势数据
  if (statisticsData.value && statisticsData.value.visitTrends) {
    const trends = statisticsData.value.visitTrends
    // 确保月份数据按时间顺序排序
    const sortedTrends = [...trends].sort((a, b) => {
      const aDate = a.month
      const bDate = b.month
      return aDate.localeCompare(bDate)
    })
    
    const months = sortedTrends.map(item => item.month)
    const visitData = sortedTrends.map(item => item.visit_count)
    return { months, visitData }
  }
  
  return {
    months: [],
    visitData: []
  }
})

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  // 如果已存在chart实例，销毁重建
  if (chart) {
    chart.dispose()
  }
  
  // 创建ECharts实例
  chart = echarts.init(chartRef.value)
  
  // 获取实际数据，如果没有则使用默认数据
  const { months, visitData: visitCountData } = visitTrends.value
  
  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: '#36CBBE',
          width: 1,
          type: 'solid'
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '16',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: months.length > 0 ? months : ['本月'],
      axisLine: {
        lineStyle: {
          color: '#E0E6F1'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#EBEEF5',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    series: [
      {
        name: '浏览量',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        showSymbol: true,
        lineStyle: {
          width: 3,
          color: '#36CBBE'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(54, 203, 190, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(54, 203, 190, 0.05)'
            }
          ])
        },
        emphasis: {
          focus: 'series',
          itemStyle: {
            color: '#36CBBE',
            borderColor: '#fff',
            borderWidth: 2
          }
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
          color: '#303133',
          fontSize: 12
        },
        data: visitCountData.length > 0 ? visitCountData : [0]
      }
    ]
  }
  
  // 使用配置项设置图表
  chart.setOption(option)
  
  // 窗口大小变化时自动调整图表大小
  window.addEventListener('resize', () => {
    chart && chart.resize()
  })
}

// 当统计数据变化时更新图表
watch(() => statisticsData.value, (newVal) => {
  if (newVal) {
    initChart()
  }
}, { deep: true })

onMounted(() => {
  getVisitData()
  initChart()
})
</script>

<style lang="scss" scoped>
.trend-chart-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  height: 400px;
  margin-top: 20px;
  
  .chart-header {
    margin-bottom: 10px;
    
    .chart-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
  }
  
  .chart-container {
    width: 100%;
    height: 330px;
  }
}
</style> 